package com.warom.sdg.websocket;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.gson.JsonObject;
import com.warom.sdg.R;
import com.warom.sdg.service.PlcDataService;
import com.warom.sdg.ui.activity.MainActivity;
import com.warom.sdg.util.DeviceUtils;
import com.warom.sdg.util.LogUtils;
import com.warom.sdg.websocket.handler.CommandHandler;
import com.warom.sdg.websocket.listener.WebSocketMessageListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import okio.ByteString;

/**
 * WebSocket服务
 * 作为前台服务运行，保持与服务器的WebSocket连接
 */
public class WebSocketService extends Service {
    private static final String TAG = "WebSocketService";
    
    // 通知相关
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "websocket_service_channel";
    private static final String CHANNEL_NAME = "WebSocket服务";
    
    // 广播动作
    public static final String ACTION_WEBSOCKET_CONNECTED = "com.warom.sdg.ACTION_WEBSOCKET_CONNECTED";
    public static final String ACTION_WEBSOCKET_DISCONNECTED = "com.warom.sdg.ACTION_WEBSOCKET_DISCONNECTED";
    public static final String ACTION_WEBSOCKET_MESSAGE = "com.warom.sdg.ACTION_WEBSOCKET_MESSAGE";
    
    // 广播Extra
    public static final String EXTRA_MESSAGE_TYPE = "message_type";
    public static final String EXTRA_MESSAGE_DATA = "message_data";
    
    // WebSocket客户端
    private WebSocketClient webSocketClient;
    private WebSocketMessageHandler messageHandler;
    
    // 心跳定时器
    private ScheduledExecutorService scheduler;
    private ScheduledFuture<?> heartbeatTask;
    
    // 服务绑定器
    private final IBinder binder = new WebSocketBinder();
    
    // 消息监听器列表
    private List<WebSocketMessageListener> messageListeners = new ArrayList<>();
    
    // 主线程Handler
    private Handler mainHandler;
    
    // 服务运行状态
    private boolean isRunning = false;
    
    // PLC数据服务
    private PlcDataService plcDataService;
    
    /**
     * WebSocket服务绑定器
     */
    public class WebSocketBinder extends Binder {
        public WebSocketService getService() {
            return WebSocketService.this;
        }
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "WebSocket服务创建");
        
        // 初始化主线程Handler
        mainHandler = new Handler(Looper.getMainLooper());
        
        // 创建定时任务执行器
        scheduler = Executors.newScheduledThreadPool(1);
        
        // WebSocket消息处理器会在startWebSocketClient中初始化
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "WebSocket服务启动");
        
        // 如果服务已经在运行，直接返回
        if (isRunning) {
            return START_STICKY;
        }
        
        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification(getString(R.string.websocket_running)));
        
        // 启动WebSocket连接
        startWebSocketClient();
        
        // 更新运行状态
        isRunning = true;
        
        // 如果服务被杀死，系统会尝试重新创建服务
        return START_STICKY;
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "WebSocket服务绑定");
        return binder;
    }
    
    @Override
    public void onDestroy() {
        Log.d(TAG, "WebSocket服务销毁");
        
        // 停止WebSocket连接
        stopWebSocketClient();
        
        // 停止心跳任务
        stopHeartbeat();
        
        // 关闭定时任务执行器
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();
        }
        
        super.onDestroy();
    }
    
    /**
     * 启动WebSocket客户端
     */
    private void startWebSocketClient() {
        // 获取WebSocket配置
        WebSocketConfig config = WebSocketConfig.getInstance(this);
        String wsUrl = config.getWebSocketUrl();
        
        Log.d(TAG, "启动WebSocket客户端: " + wsUrl);
        
        // 创建WebSocket客户端
        webSocketClient = new WebSocketClient(wsUrl);
        webSocketClient.setMessageListener(createWebSocketListener());
        
        // 创建命令回调
        CommandHandler.CommandCallback commandCallback = new CommandHandler.CommandCallback() {
            @Override
            public void reconnect() {
                WebSocketService.this.reconnect();
            }
            
            @Override
            public void startHeartbeat() {
                WebSocketService.this.startHeartbeat();
            }
            
            @Override
            public void sendMessage(String message) {
                WebSocketService.this.sendMessage(message);
            }
            
            @Override
            public PlcDataService getPlcDataService() {
                return WebSocketService.this.plcDataService;
            }
        };
        
        // 初始化消息处理器
        messageHandler = new WebSocketMessageHandler(this, webSocketClient, commandCallback);
        messageHandler.setMessageListener(createMessageListener());
        
        // 连接WebSocket
        webSocketClient.connect();
        
        // 启动心跳任务
        startHeartbeat();
    }
    
    /**
     * 停止WebSocket客户端
     */
    private void stopWebSocketClient() {
        if (webSocketClient != null) {
            webSocketClient.disconnect();
            webSocketClient = null;
        }
    }
    
    /**
     * 重新连接WebSocket
     */
    public void reconnect() {
        Log.d(TAG, "手动重新连接WebSocket");
        
        // 停止现有连接
        stopWebSocketClient();
        
        // 启动新连接
        startWebSocketClient();
    }
    
    /**
     * 启动心跳任务
     */
    private void startHeartbeat() {
        // 停止现有心跳任务
        stopHeartbeat();
        
        // 获取心跳间隔
        int interval = WebSocketConfig.getInstance(this).getHeartbeatInterval();
        
        // 创建新的心跳任务
        heartbeatTask = scheduler.scheduleAtFixedRate(
                this::sendHeartbeat,
                interval,
                interval,
                TimeUnit.SECONDS);
        
        Log.d(TAG, "心跳任务已启动，间隔: " + interval + "秒");
    }
    
    /**
     * 停止心跳任务
     */
    private void stopHeartbeat() {
        if (heartbeatTask != null && !heartbeatTask.isCancelled()) {
            heartbeatTask.cancel(true);
            heartbeatTask = null;
            Log.d(TAG, "心跳任务已停止");
        }
    }
    
    /**
     * 发送心跳消息
     */
    private void sendHeartbeat() {
        try {
            if (webSocketClient != null &&
                webSocketClient.getState() == WebSocketClient.ConnectionState.CONNECTED) {

                // 创建并发送心跳消息
                String heartbeatMessage = WebSocketMessageHandler.createHeartbeatMessage();
                webSocketClient.sendMessage(heartbeatMessage);

                Log.d(TAG, "已发送心跳消息");
            }
        } catch (Exception e) {
            Log.e(TAG, "发送心跳消息异常: " + e.getMessage(), e);
        }
    }
    
    /**
     * 发送消息
     * @param message 要发送的消息
     * @return 是否发送成功
     */
    public boolean sendMessage(String message) {
        if (webSocketClient != null && 
            webSocketClient.getState() == WebSocketClient.ConnectionState.CONNECTED) {
            return webSocketClient.sendMessage(message);
        }
        return false;
    }
    
    /**
     * 发送数据消息
     * @param data 数据内容
     * @return 是否发送成功
     */
    public boolean sendDataMessage(JsonObject data) {
        String message = WebSocketMessageHandler.createDataMessage(data);
        return sendMessage(message);
    }
    
    /**
     * 创建WebSocket监听器
     * @return WebSocket监听器
     */
    private WebSocketClient.WebSocketMessageListener createWebSocketListener() {
        return new WebSocketClient.WebSocketMessageListener() {
            @Override
            public void onConnected() {
                Log.d(TAG, "WebSocket已连接");
                
                // 更新通知
                updateNotification(getString(R.string.websocket_connected));
                
                // 记录日志
                LogUtils.logOperation("WebSocket", "连接", "WebSocket已连接");
                
                // 发送广播
                sendBroadcast(new Intent(ACTION_WEBSOCKET_CONNECTED));
            }
            
            @Override
            public void onDisconnected() {
                Log.d(TAG, "WebSocket已断开");
                
                // 更新通知
                updateNotification(getString(R.string.websocket_disconnected));
                
                // 记录日志
                LogUtils.logOperation("WebSocket", "断开", "WebSocket连接已断开");
                
                // 发送广播
                sendBroadcast(new Intent(ACTION_WEBSOCKET_DISCONNECTED));
            }
            
            @Override
            public void onMessage(String text) {
                // 处理收到的消息
                messageHandler.handleMessage(text);
                
                // 发送广播
                Intent intent = new Intent(ACTION_WEBSOCKET_MESSAGE);
                intent.putExtra(EXTRA_MESSAGE_TYPE, "text");
                intent.putExtra(EXTRA_MESSAGE_DATA, text);
                sendBroadcast(intent);
            }
            
            @Override
            public void onMessage(ByteString bytes) {
                // 暂不处理二进制消息
                Log.d(TAG, "收到二进制消息，暂不处理");
            }
            
            @Override
            public void onError(String error) {
                Log.e(TAG, "WebSocket错误: " + error);
                
                // 记录日志
                LogUtils.logOperation("WebSocket", "错误", "WebSocket错误: " + error);
                
                // 更新通知
                updateNotification(getString(R.string.websocket_error, error));
            }
        };
    }
    
    /**
     * 创建消息监听器
     * @return 消息监听器
     */
    private WebSocketMessageListener createMessageListener() {
        return new WebSocketMessageListener() {
            @Override
            public void onHeartbeat(JsonObject data) {
                // 心跳消息，不需要特殊处理
                notifyMessageListeners(listener -> listener.onHeartbeat(data));
            }
            
            @Override
            public void onCommand(String command, JsonObject data) {
                // 只需通知监听器，具体处理已经在MessageHandler中完成
                notifyMessageListeners(listener -> listener.onCommand(command, data));
            }
            
            @Override
            public void onNotification(String title, String message, JsonObject data) {
                // 只需通知监听器，具体处理已经在MessageHandler中完成
                notifyMessageListeners(listener -> 
                    listener.onNotification(title, message, data));
            }
            
            @Override
            public void onData(JsonObject data) {
                // 通知监听器
                notifyMessageListeners(listener -> listener.onData(data));
            }
            
            @Override
            public void onUnknownMessage(String type, JsonObject data) {
                Log.d(TAG, "处理未知类型消息: " + type);
                
                // 通知监听器
                notifyMessageListeners(listener -> listener.onUnknownMessage(type, data));
            }
        };
    }
    
    // 这些方法已经移动到CommandHandler中，不再需要
    
    /**
     * 创建通知
     * @param text 通知内容
     * @return Notification对象
     */
    private Notification createNotification(String text) {
        // 创建通知渠道
        createNotificationChannel();
        
        // 创建点击通知时的Intent
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
        
        // 创建通知
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(getString(R.string.websocket_notification_title))
                .setContentText(text)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();
    }
    
    /**
     * 创建通知渠道
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_LOW);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    
    /**
     * 更新通知
     * @param text 通知内容
     */
    private void updateNotification(String text) {
        NotificationManager notificationManager = 
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        
        notificationManager.notify(NOTIFICATION_ID, createNotification(text));
    }
    
    // 已移动到NotificationHandler中
    
    /**
     * 注册消息监听器
     * @param listener 消息监听器
     */
    public void registerMessageListener(WebSocketMessageListener listener) {
        if (listener != null && !messageListeners.contains(listener)) {
            messageListeners.add(listener);
        }
    }
    
    /**
     * 注销消息监听器
     * @param listener 消息监听器
     */
    public void unregisterMessageListener(WebSocketMessageListener listener) {
        messageListeners.remove(listener);
    }
    
    /**
     * 通知所有消息监听器
     * @param action 监听器操作
     */
    private void notifyMessageListeners(ListenerAction action) {
        for (WebSocketMessageListener listener : new ArrayList<>(messageListeners)) {
            try {
                action.execute(listener);
            } catch (Exception e) {
                Log.e(TAG, "通知监听器异常: " + e.getMessage(), e);
            }
        }
    }
    
    /**
     * 监听器操作接口
     */
    private interface ListenerAction {
        void execute(WebSocketMessageListener listener);
    }
    
    /**
     * 获取WebSocket连接状态
     * @return 连接状态
     */
    public WebSocketClient.ConnectionState getConnectionState() {
        return webSocketClient != null ? webSocketClient.getState() : 
                WebSocketClient.ConnectionState.DISCONNECTED;
    }
    
    /**
     * 设置PLC数据服务
     * @param plcDataService PLC数据服务
     */
    public void setPlcDataService(PlcDataService plcDataService) {
        this.plcDataService = plcDataService;
        Log.d(TAG, "已设置PLC数据服务到WebSocket服务");
    }
} 